package com.xca.znb.view;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.bumptech.glide.Glide;
import com.xca.znb.R;
import com.xca.znb.entity.Cart;
import com.xca.znb.entity.Goods;
import com.xca.znb.entity.Local;
import com.xca.znb.model.impl.CartClearingImpl;
import com.xca.znb.presenter.CartClearingPresenter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class CartClearing extends AppCompatActivity {
    private ImageButton backBtn , toLocal ;
    private TextView showLocal , showName , showId , needPay , totalPay ;
    private ListView listView ;
    private Button payBtn ;
    private ArrayList<Integer> idList = new ArrayList<>();
    private List<Cart> cartList = new ArrayList<>();
    private ArrayAdapter<Cart> adapter ;
    private CartClearingPresenter presenter ;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cart_clearing);
        initView();

        CartClearingImpl cartClearingImpl = new CartClearingImpl(this);
        presenter = new CartClearingPresenter(cartClearingImpl);

        if (getIntent().getExtras() != null) {
            // 使用Serializable方式获取ArrayList
            idList = (ArrayList<Integer>) getIntent().getSerializableExtra("cart_list_id");
        }
        Intent intent = getIntent() ;
        int localId = intent.getIntExtra("cart_local_id" , 0);

        showLocalMessage();
        toLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(CartClearing.this , LocalCartActivity.class);
                intent.putExtra("cartLocal_idList" , idList);
                intent.putExtra("cartLocal_localId" , localId);
                startActivity(intent);
                finish();
                idList.clear();
            }
        });


        payBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1 = new Intent(CartClearing.this , EndPayCart.class);
                intent1.putExtra("toEndPayCartList" , idList);
                intent1.putExtra("toEndPayCartLocal" , localId);
                startActivity(intent1);
                idList.clear();
            }
        });


        backBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                idList.clear();
                onBackPressed();
            }
        });
    }


    private void showAdapter(){
        if (getIntent().getExtras() != null) {
            // 使用Serializable方式获取ArrayList
            idList = (ArrayList<Integer>) getIntent().getSerializableExtra("cart_list_id");
        }
        //将购物车id转化为购物车对象
        for (int id : idList){
            Cart cart = presenter.getCartById(id);
            cartList.add(cart);
        }

        setListViewAdapter();
        listView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }
    private void showMoney(){
        double needPayMoney = 0 ;
        if (!idList.isEmpty()){
            for (int id : idList){
                Cart cart  = presenter.getCartById(id);
                Goods goods = presenter.getGoodsById(cart.getGoodsId());
                needPayMoney = needPayMoney + (goods.getPrice() * cart.getNum());
                needPay.setText(String.valueOf(needPayMoney));
                totalPay.setText(String.valueOf(needPayMoney));
            }
        }else {
            totalPay.setText("0");
            needPay.setText("0");
        }
    }
    private void showLocalMessage(){
        Intent intent = getIntent() ;
        int localId = intent.getIntExtra("cart_local_id" , 0);
        Local local = presenter.getLocalById(localId);
        showLocal.setText(local.getAddress());
        showName.setText(local.getName());
        showId.setText(local.getPhone());
    }
    private void initView(){
        backBtn = findViewById(R.id.cart_clearing_back);
        toLocal = findViewById(R.id.cart_clearing_choose_local);
        showLocal = findViewById(R.id.cart_clearing_local);
        showName = findViewById(R.id.cart_clearing_user_name) ;
        showId = findViewById(R.id.cart_clearing_user_id);
        listView = findViewById(R.id.cart_clearing_listView);
        needPay = findViewById(R.id.cart_clearing_needPay);
        totalPay = findViewById(R.id.cart_clearing_pay);
        payBtn = findViewById(R.id.cart_clearing_submit);
    }

    private void setListViewAdapter(){
        adapter = new ArrayAdapter<Cart>(this , R.layout.cart_cleaning_item , R.id.cart_cleaning_item_name , cartList){
            @NonNull
            public View getView(int position , View converView , ViewGroup parent){
                View view = super.getView(position, converView, parent);
                ImageView goodsImg = view.findViewById(R.id.cart_cleaning_item_img);
                TextView goodsName = view.findViewById(R.id.cart_cleaning_item_name);
                ImageButton minus = view.findViewById(R.id.cart_cleaning_item_minus);
                TextView goodsNum = view.findViewById(R.id.cart_cleaning_item_num);
                ImageButton add = view.findViewById(R.id.cart_cleaning_item_add);
                TextView goodsPay = view.findViewById(R.id.cart_cleaning_item_money);
                Cart cart = getItem(position);
                assert cart != null;
                Goods goods = presenter.getGoodsById(cart.getGoodsId());
                if (goods != null){
                    Glide.with(CartClearing.this)
                                    .load(goods.getFirst_image())
                                            .into(goodsImg);
                    goodsName.setText(goods.getName());
                    goodsNum.setText(String.valueOf(cart.getNum()));
                    goodsPay.setText(String.valueOf(goods.getPrice() * cart.getNum()));
                }

                minus.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int num = Integer.parseInt(goodsNum.getText().toString());
                        if (num >1){
                            num = num - 1 ;
                            goodsNum.setText(String.valueOf(num));
                            goodsPay.setText(String.valueOf(goods.getPrice() * num ));
                            presenter.updateCartNumById(cart.getId() , num);
                            showMoney();
                        }else {
                            Toast.makeText(CartClearing.this, "亲，不能再少了", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
                add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int num = Integer.parseInt(goodsNum.getText().toString());
                        num = num + 1 ;
                        goodsNum.setText(String.valueOf(num));
                        goodsPay.setText(String.valueOf(goods.getPrice() * num ));
                        presenter.updateCartNumById(cart.getId() , num);
                        showMoney();
                    }
                });
                goodsNum.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(CartClearing.this);
                        builder.setMessage("输入商品数量");
                        final EditText editText = new EditText(CartClearing.this);
                        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
                        builder.setView(editText);
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                String getNum = editText.getText().toString().trim();
                                if (getNum.isEmpty()){
                                    Toast.makeText(CartClearing.this, "请输入需求数量", Toast.LENGTH_SHORT).show();
                                }else {
                                    int num = Integer.parseInt(getNum);
                                    if (num >= 1){
                                        goodsNum.setText(getNum);
                                        goodsPay.setText(String.valueOf(goods.getPrice() * num));
                                        presenter.updateCartNumById(cart.getId() , num);
                                        Cart cart1 = presenter.getCartById(cart.getId());
                                        cartList.set(position , cart1);
                                        adapter.notifyDataSetChanged();
                                        showMoney();
                                    }else {
                                        Toast.makeText(CartClearing.this, "商品数量输入不规范", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        });
                        builder.create().show();
                    }
                });

                return view ;
            }
        };
    }

    @Override
    protected void onResume() {
        super.onResume();
        showLocalMessage();
        showMoney();
        showAdapter();
    }
}